# R script for replicating results in appendix section "Description of Variables"
# Zhai & Garside 2022
# original device: MacPro 13, R 4.1.2
# recommended working directory: Desktop

setwd("~/Desktop") # default wkd
rm(list = ls())

# pkgs --------------------------------------------------------------------

if (!require("pacman")) install.packages("pacman")
pacman::p_load(sf, spdep)

# figure 4 ----------------------------------------------------------------

gadm.de4 <- readRDS("data_gadm_4.RDS")
coords.gadm.de4 <- st_centroid(st_geometry(gadm.de4), of_largest_polygon = TRUE)
nlist.de4.knn <- knearneigh(coords.gadm.de4, k=5)
nlist.de4.queen <- poly2nb(gadm.de4, row.names = gadm.de4$NAME_4, queen = TRUE)

png("~/Desktop/appendix_figure4.png", width = 9, height = 4, units = 'in', res = 300)
par(mfrow = c(1,2), mar = c(2, 1, 2, 1))
plot(st_geometry(gadm.de4), border="grey")
plot(knn2nb(nlist.de4.knn), coords.gadm.de4, add=TRUE, col="red", cex = 0.1)
title(main = "A. K nearest neighbours (k = 5)")
plot(st_geometry(gadm.de4), border="grey")
plot(nlist.de4.queen, coords.gadm.de4, add=TRUE, col="blue", cex = 0.1)
title(main = "B. Contiguous neighbours (queen)")
dev.off()

# cleanup -----------------------------------------------------------------

pacman::p_unload("all")
rm(list = ls())
